<template>
  <div class="p-2">
    <!-- 接入管理 - 客户端管理 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
        <el-form-item label="客户端名称" prop="clientName">
          <el-input v-model="queryParams.clientName" placeholder="请输入客户端名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="客户端ID" prop="clientId">
          <el-input v-model="queryParams.clientId" placeholder="请输入客户端ID" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="连接状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="在线" value="1" />
            <el-option label="离线" value="0" />
            <el-option label="异常" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户端类型" prop="clientType">
          <el-select v-model="queryParams.clientType" placeholder="请选择类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="设备客户端" value="device" />
            <el-option label="应用客户端" value="app" />
            <el-option label="网关客户端" value="gateway" />
            <el-option label="第三方客户端" value="third_party" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增客户端</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="Refresh" @click="handleRefresh">刷新连接状态</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table v-loading="loading" :data="clientList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="客户端ID" prop="clientId" width="180" show-overflow-tooltip />
        <el-table-column label="客户端名称" prop="clientName" width="150" show-overflow-tooltip />
        <el-table-column label="客户端类型" prop="clientType" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getClientTypeTag(scope.row.clientType)">{{ getClientTypeText(scope.row.clientType)
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="连接状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="IP地址" prop="ipAddress" width="140" show-overflow-tooltip />
        <el-table-column label="端口" prop="port" width="80" align="center" />
        <el-table-column label="协议类型" prop="protocol" width="100" align="center">
          <template #default="scope">
            <el-tag type="info" size="small">{{ scope.row.protocol }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="认证方式" prop="authType" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getAuthTypeTag(scope.row.authType)" size="small">{{ getAuthTypeText(scope.row.authType)
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="连接时间" prop="connectTime" width="160" show-overflow-tooltip />
        <el-table-column label="最后心跳" prop="lastHeartbeat" width="160" show-overflow-tooltip />
        <el-table-column label="数据流量(KB)" prop="dataFlow" width="120" align="center">
          <template #default="scope">
            <span style="color: #409EFF">{{ scope.row.dataFlow }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="断开连接" placement="top" v-if="scope.row.status === '1'">
              <el-button link type="warning" icon="SwitchButton" @click="handleDisconnect(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="强制连接" placement="top" v-if="scope.row.status === '0'">
              <el-button link type="success" icon="Connection" @click="handleConnect(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <Pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改客户端对话框 -->
    <ClientFormDialog v-model:visible="dialog.visible" :title="dialog.title" :form-data="form" @submit="submitForm"
      @cancel="cancel" />

    <!-- 客户端详情对话框 -->
    <ClientDetailDialog v-model:visible="detailDialog.visible" :data="detailDialog.data" />
  </div>
</template>

<script setup name="ClientManage" lang="ts">
import { getCurrentInstance, reactive, ref, toRefs, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import type { ClientInfo, ClientQueryParams, ClientFormData } from '@/api/IOT/accessManage/clientManage/types'
import { parseTime } from '@/utils/ruoyi'
import ClientFormDialog from './components/ClientFormDialog.vue'
import ClientDetailDialog from './components/ClientDetailDialog.vue'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const loading = ref(false)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const clientList = ref([])
const queryFormRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  clientName: '',
  clientId: '',
  status: '',
  clientType: ''
})

// 表单数据
const form = reactive({
  clientId: '',
  clientName: '',
  clientType: '',
  protocol: '',
  authType: '',
  ipAddress: '',
  port: null,
  status: '1',
  authInfo: '',
  remark: ''
})

// 对话框
const dialog = reactive({
  visible: false,
  title: ''
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: null
})

// 表单验证规则
const rules = reactive({
  clientId: [{ required: true, message: '客户端ID不能为空', trigger: 'blur' }],
  clientName: [{ required: true, message: '客户端名称不能为空', trigger: 'blur' }],
  clientType: [{ required: true, message: '客户端类型不能为空', trigger: 'change' }],
  protocol: [{ required: true, message: '协议类型不能为空', trigger: 'change' }],
  authType: [{ required: true, message: '认证方式不能为空', trigger: 'change' }],
  ipAddress: [{ required: true, message: 'IP地址不能为空', trigger: 'blur' }],
  port: [{ required: true, message: '端口不能为空', trigger: 'blur' }]
})

// 获取客户端类型标签样式
const getClientTypeTag = (type: string) => {
  switch (type) {
    case 'device': return 'primary'
    case 'app': return 'success'
    case 'gateway': return 'warning'
    case 'third_party': return 'info'
    default: return 'primary'
  }
}

// 获取客户端类型文本
const getClientTypeText = (type: string) => {
  switch (type) {
    case 'device': return '设备客户端'
    case 'app': return '应用客户端'
    case 'gateway': return '网关客户端'
    case 'third_party': return '第三方客户端'
    default: return '未知'
  }
}

// 获取状态标签样式
const getStatusTag = (status: string) => {
  switch (status) {
    case '1': return 'success'
    case '0': return 'danger'
    case '2': return 'warning'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case '1': return '在线'
    case '0': return '离线'
    case '2': return '异常'
    default: return '未知'
  }
}

// 获取认证方式标签样式
const getAuthTypeTag = (type: string) => {
  switch (type) {
    case 'username_password': return 'primary'
    case 'token': return 'success'
    case 'certificate': return 'warning'
    case 'api_key': return 'info'
    default: return 'primary'
  }
}

// 获取认证方式文本
const getAuthTypeText = (type: string) => {
  switch (type) {
    case 'username_password': return '用户名密码'
    case 'token': return 'Token认证'
    case 'certificate': return '证书认证'
    case 'api_key': return 'API密钥'
    default: return '未知'
  }
}

// 本地虚拟延迟（随机不超过1.5s）
const delayRandom = (min = 300, max = 1500) => new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * (max - min + 1)) + min))

// 本地客户端数据源
const allClients = ref<ClientInfo[]>([])

// 初始化客户端数据
const initClients = () => {
  if (allClients.value.length) return
  const types = ['device','app','gateway','third_party']
  const protocols = ['MQTT','HTTP','TCP']
  const auths = ['username_password','token','certificate','api_key']
  const list: ClientInfo[] = []
  for (let i = 1; i <= 48; i++) {
    const status = (i % 3 === 0) ? '0' : (i % 5 === 0 ? '2' : '1')
    list.push({
      clientId: `CLIENT-${String(i).padStart(4, '0')}`,
      clientName: `客户端-${i}`,
      clientType: types[i % types.length],
      status,
      ipAddress: `192.168.${i % 10}.${(i % 200) + 10}`,
      port: 1883 + (i % 10),
      protocol: protocols[i % protocols.length],
      authType: auths[i % auths.length],
      connectTime: new Date(Date.now() - i * 3600_000).toLocaleString(),
      lastHeartbeat: new Date(Date.now() - i * 600_000).toLocaleString(),
      dataFlow: 100 + i * 5,
      remark: i % 7 === 0 ? '检查连接质量' : ''
    } as any)
  }
  allClients.value = list
}

initClients()

// 查询客户端列表（本地虚拟请求）
const getList = async () => {
  loading.value = true
  try {
    await delayRandom()
    let filtered = [...allClients.value]
    if (queryParams.clientName) filtered = filtered.filter(c => c.clientName.includes(queryParams.clientName))
    if (queryParams.clientId) filtered = filtered.filter(c => c.clientId.includes(queryParams.clientId))
    if (queryParams.status) filtered = filtered.filter(c => c.status === queryParams.status)
    if (queryParams.clientType) filtered = filtered.filter(c => c.clientType === queryParams.clientType)
    const start = (queryParams.pageNum - 1) * queryParams.pageSize
    const end = start + queryParams.pageSize
    clientList.value = filtered.slice(start, end)
    total.value = filtered.length
  } catch (error) {
    console.error('获取客户端列表失败:', error)
    ElMessage.error('获取客户端列表失败')
  } finally {
    loading.value = false
  }
}

// 修改按钮操作（本地虚拟请求）
const handleUpdate = (row?: any) => {
  reset()
  const cid = row?.clientId || (ids.value as any[])[0]
  const found = allClients.value.find(c => c.clientId === cid)
  if (found) {
    Object.assign(form, found)
  }
  dialog.visible = true
  dialog.title = '修改客户端'
}

// 删除按钮操作（本地虚拟请求）
const handleDelete = async (row?: any) => {
  const clientIds: string[] = row?.clientId ? [row.clientId] : (ids.value as any[])
  const clientNames = clientList.value.filter(item => clientIds.includes(item.clientId)).map(item => item.clientName)
  ElMessageBox.confirm('是否确认删除客户端"' + clientNames.join(',') + '"？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      await delayRandom()
      const idSet = new Set(clientIds)
      allClients.value = allClients.value.filter(c => !idSet.has(c.clientId))
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    } finally {
      loading.value = false
    }
  })
}

// 导出按钮操作（本地虚拟请求）
const handleExport = async () => {
  try {
    await delayRandom()
    const data = clientList.value
    const header = ['客户端ID','客户端名称','类型','状态','IP地址','端口','协议类型','认证方式','连接时间','最后心跳','数据流量(KB)','备注']
    const rows = data.map(c => [c.clientId, c.clientName, getClientTypeText(c.clientType), getStatusText(c.status), c.ipAddress, c.port, c.protocol, getAuthTypeText(c.authType), c.connectTime, c.lastHeartbeat, c.dataFlow, c.remark || ''])
    const csv = [header.join(','), ...rows.map(r => r.map(v => `"${String(v).replace(/"/g, '""')}"`).join(','))].join('\n')
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `客户端列表_${Date.now()}.csv`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 提交按钮（本地新增/修改）
const submitForm = async () => {
  try {
    loading.value = true
    await delayRandom()
    const exists = allClients.value.findIndex(c => c.clientId === form.clientId)
    if (exists !== -1) {
      allClients.value[exists] = { ...allClients.value[exists], ...form }
      ElMessage.success('修改成功')
    } else {
      const newId = `CLIENT-${String(Math.max(0, ...allClients.value.map(c => parseInt((c.clientId||'').split('-')[1] || '0'))) + 1).padStart(4, '0')}`
      const record = { ...form, clientId: form.clientId || newId }
      allClients.value.unshift(record as any)
      ElMessage.success('新增成功')
    }
    dialog.visible = false
    getList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  } finally {
    loading.value = false
  }
}

// 取消按钮
const cancel = () => {
  dialog.visible = false
  reset()
}

// 表单重置
const reset = () => {
  form.clientId = ''
  form.clientName = ''
  form.clientType = ''
  form.protocol = ''
  form.authType = ''
  form.ipAddress = ''
  form.port = null
  form.status = '1'
  form.authInfo = ''
  form.remark = ''
}

// 查询按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  queryParams.clientName = ''
  queryParams.clientId = ''
  queryParams.status = ''
  queryParams.clientType = ''
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.clientId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  dialog.visible = true
  dialog.title = '添加客户端'
}

// 查看详情按钮操作
const handleView = (row: any) => {
  // 添加一些额外的详情数据
  const detailData = {
    ...row,
    subscribeTopics: ['sensor/temperature', 'sensor/humidity', 'device/status'],
    publishTopics: ['data/upload', 'alarm/fire', 'heartbeat'],
    messageCount: Math.floor(Math.random() * 10000) + 1000,
    qosLevel: Math.floor(Math.random() * 3),
    keepAlive: 60,
    createTime: new Date(Date.now() - Math.random() * 30 * 24 * 3600 * 1000).toLocaleString(),
    updateTime: new Date(Date.now() - Math.random() * 7 * 24 * 3600 * 1000).toLocaleString()
  }
  detailDialog.data = detailData
  detailDialog.visible = true
}

// 断开连接操作
const handleDisconnect = async (row: any) => {
  ElMessageBox.confirm(`确认要断开客户端"${row.clientName}"的连接吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      await delayRandom()
      // 更新客户端状态为离线
      const client = allClients.value.find(c => c.clientId === row.clientId)
      if (client) {
        client.status = '0'
        client.lastHeartbeat = new Date().toLocaleString()
      }
      ElMessage.success('断开连接成功')
      getList()
    } catch (error) {
      console.error('断开连接失败:', error)
      ElMessage.error('断开连接失败')
    } finally {
      loading.value = false
    }
  })
}

// 强制连接操作
const handleConnect = async (row: any) => {
  ElMessageBox.confirm(`确认要强制连接客户端"${row.clientName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      loading.value = true
      await delayRandom()
      // 更新客户端状态为在线
      const client = allClients.value.find(c => c.clientId === row.clientId)
      if (client) {
        client.status = '1'
        client.connectTime = new Date().toLocaleString()
        client.lastHeartbeat = new Date().toLocaleString()
      }
      ElMessage.success('连接成功')
      getList()
    } catch (error) {
      console.error('连接失败:', error)
      ElMessage.error('连接失败')
    } finally {
      loading.value = false
    }
  })
}

// 刷新连接状态
const handleRefresh = async () => {
  try {
    loading.value = true
    await delayRandom()
    // 模拟刷新所有客户端的连接状态
    allClients.value.forEach(client => {
      // 随机更新一些客户端的状态和心跳时间
      if (Math.random() > 0.7) {
        client.lastHeartbeat = new Date().toLocaleString()
        // 有小概率改变状态
        if (Math.random() > 0.9) {
          client.status = client.status === '1' ? '0' : '1'
        }
      }
    })
    ElMessage.success('刷新连接状态成功')
    getList()
  } catch (error) {
    console.error('刷新失败:', error)
    ElMessage.error('刷新失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载
onMounted(() => {
  getList()
})
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>